//
//  DDCompanyImageViewController.m
//  DingDongZP
//
//  Created by weily on 16/4/24.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDCompanyImageViewController.h"
#import "DDCompanyImageCell.h"
#import "DDAvatarPickerView.h"
#import "CCImageGetter.h"
#import "DDAPIGenerate.h"
#import "DDCompanyHomeService.h"

/**
 *  公司风采
 */
@interface DDCompanyImageViewController ()
<UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *selectedImgs;

@end

@implementation DDCompanyImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"公司风采";
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(20, 10, 0, 10);
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    layout.itemSize = CGSizeMake((SCREEN_WIDTH-30)/2, 100);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = COLOR_BACKGROUND;
    [self.collectionView registerNib:[UINib nibWithNibName:@"DDCompanyImageCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionView];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
//    self.navigationItem.rightBarButtonItem = self.confirmItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - evnets
- (void)actionConfirm:(UIButton *)btn
{
    
}

#pragma mark - delegates
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 5;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    DDCompanyImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (indexPath.row < self.companyInfo.companyshow.count) {
        
        DDCompanyshow *show = self.companyInfo.companyshow[indexPath.row];
        NSString *url = [DDAPIGenerate imageURLWithPath:show.show_logo];
        [cell setImageWithURL:url];
//        [cell setImageWithImage:_selectedImgs[indexPath.row]];
        
        __weak typeof(self) weakSelf = self;
        cell.replaceImage = ^(int index) {
            [weakSelf replaceImageWithImageAtIndex:indexPath.row];
        };
    }
    else {
        if (indexPath.row == _companyInfo.companyshow.count) {
            [cell setDescInfo:[NSString stringWithFormat:@"还可上传%ld张图片", 5-_companyInfo.companyshow.count]];
        }
    }
    return cell;
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= self.companyInfo.companyshow.count) {
        WEAKSELF;
        DDAvatarPickerView *avatar = [DDAvatarPickerView instanciate];
        avatar.showDefaultsImgs = NO;
        [avatar showWithAnimation:YES];
        avatar.didSelectAvatarType = ^(NSInteger type) {
            if (type == 0) {
                [[CCImageGetter sharedImageGetter] takePhoto];
                [CCImageGetter sharedImageGetter].callback = ^(UIImage *img) {
                    [weakSelf didGetImageFromSystem:img withIndex:indexPath.row];
                };
            }
            else if (type == 1) {
                [[CCImageGetter sharedImageGetter] selectFromAlbum];
                [CCImageGetter sharedImageGetter].callback = ^(UIImage *img) {
                    [weakSelf didGetImageFromSystem:img withIndex:indexPath.row];
                };
            }
        };
    }
}

- (void)didGetImageFromSystem:(UIImage *)img withIndex:(NSInteger)idx
{
    [self showLoading];
    
    //  替换
    if (idx < self.companyInfo.companyshow.count) {
        DDCompanyshow *show = [self.companyInfo.companyshow objectAtIndex:idx];
        
        [[DDCompanyHomeService sharedService] deleteCompanyImage:show.show_id callback:^(BOOL succ) {
            if (succ) {
                [self uploadImage:img];
            }
            else {
                [self showErrorWithText:@"替换图片失败"];
            }
        }];
    }
    else {
        [self uploadImage:img];
    }
    
    
//    if (idx < self.selectedImgs.count) {
//        [self.selectedImgs replaceObjectAtIndex:idx withObject:img];
//    }
//    else {
//        [self.selectedImgs addObject:img];
//    }
//    [self.collectionView reloadData];
}

- (void)uploadImage:(UIImage *)img
{
    [self showLoading];
    [[DDCompanyHomeService sharedService] uploadCompanyShow:img callback:^(BOOL succ) {
        
        [self hideLoading];
        if (succ) {
            [self showText:@"图片上传成功"];
            [self reloadInfos];
        }
        else {
            [self showErrorWithText:@"图片上传失败，请重试"];
        }
    }];
}

- (void)replaceImageWithImageAtIndex:(NSInteger)index
{
    DDAvatarPickerView *avatar = [DDAvatarPickerView instanciate];
    avatar.showDefaultsImgs = NO;
    [avatar showWithAnimation:YES];
    avatar.didSelectAvatarType = ^(NSInteger type) {
        if (type == 0) {
            [[CCImageGetter sharedImageGetter] takePhoto];
            [CCImageGetter sharedImageGetter].callback = ^(UIImage *img) {
                [self didGetImageFromSystem:img withIndex:index];
            };
        }
        else if (type == 1) {
            [[CCImageGetter sharedImageGetter] selectFromAlbum];
            [CCImageGetter sharedImageGetter].callback = ^(UIImage *img) {
                [self didGetImageFromSystem:img withIndex:index];
            };
        }
    };
}

- (void)reloadInfos {
    
    [self showLoading];
    [[DDCompanyHomeService sharedService] queryCompanyInfo:^(id responseObject, NSError *error) {
        
        [self hideLoading];
        if (responseObject) {
            self.companyInfo = responseObject;
            [self.collectionView reloadData];
        }
        else {
            [self showErrorWithText:error.domain];
        }
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - setter getter

- (NSMutableArray *)selectedImgs
{
	if (!_selectedImgs){
        _selectedImgs = [NSMutableArray new];
	}
	return _selectedImgs;
}

@end
